/**
 * Date:2017年12月25日上午11:09:32
 *
 */

package com.xue.action;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.filters.Canvas;
import net.coobird.thumbnailator.geometry.Positions;
import net.coobird.thumbnailator.resizers.Resizers;

/**
 * Description: demo <br/>
 * Date: 2017年12月25日 上午11:09:32 <br/>
 * 
 * @author xuejianxinokok@163.com
 */

@RequestMapping(value = DemoController.PATH)
@RestController("demoController")
public class DemoController {
	public static final String PATH = "/";
	private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(DemoController.class);

	@GetMapping("user/hello")
	public String user() {
		return "hello user";
	}

	@GetMapping("hello")
	public String hello() {
		return "hello";
	}

	@PostMapping("cropper")
	@ResponseBody
	public Map<String, Object> cropper(@RequestBody CropperOption op) throws IOException {
		// https://github.com/coobird/thumbnailator 官网
		// https://github.com/coobird/thumbnailator/wiki/Examples 官方例子
		// https://www.jianshu.com/p/27536926aa2f
		// https://www.cnblogs.com/livedian/p/15212204.html
		// https://blog.csdn.net/u012410733/article/details/116038816
		System.out.println(op);
		Map<String, Object> rs = new HashMap<>();
		boolean debug = true;
		if (debug) {
			var out = new ByteArrayOutputStream();
			cropToCanvas(op, out);
			// 上传
			// UploadUtil.upload(new ByteArrayInputStream(out.toByteArray()), String savePath, String saveName)
			
			
			String base64 = "data:image/png;base64," + Base64.getEncoder().encodeToString(out.toByteArray());
			rs.put("imgBase64", base64);
			rs.put("success", true);
		}
		// 完成后生成返回图片路径,返回到前台

		return rs;
	}

	private void cropToCanvas(CropperOption op, OutputStream out) {
		try {
			StopWatch sw = new StopWatch("cropToCanvas");
			sw.start("load");
			var originImg = getOriginImg(op.getImgId());
			sw.stop();
			sw.start("rotate&scale");
			// 2.先处理原始图片的旋转和缩放
			var imgBuilder = Thumbnails.of(originImg);
			// 如果旋转角度不为0
			if (!op.getImgRotate().equals(0.0)) {
				// 3.旋转 (角度),正数：顺时针 负数：逆时针 rotate(-90)
				imgBuilder.rotate(op.getImgRotate());
			}

			var img = imgBuilder
//					.resizer(Resizers.BILINEAR) // 效率高 平均 3s 【14641x14641】
//					.resizer(Resizers.PROGRESSIVE) //效率和BILINEAR 差不多 平均 3s 【14641x14641】
//					.resizer(Resizers.BICUBIC)//默认插值方式 效率太低平均 8s 【14641x14641】
					// 4. 缩放 ！！！这里有性能问题，放大倍数不能太大！！！！ 可能配合前端scale 来解决
					.forceSize(op.getImgW(), op.getImgH())
					.asBufferedImage();

			
			
//			var img=imgBuilder.scale(1).asBufferedImage();
			
			sw.stop();
			sw.start("crop&canvas");
			
			Thumbnails.of(img).scale(1)
					// 5. 确定裁剪区域,相对与放大和旋转后的图片
					.sourceRegion(op.getX(), op.getY(), op.getW(), op.getH())
					// 6. 合成canvas 高度940*700
					.addFilter(
							new Canvas(CropperOption.CANVAS_W, CropperOption.CANVAS_H, Positions.TOP_LEFT, Color.WHITE))
					.outputFormat("PNG").toOutputStream(out);

			sw.stop();
			System.out.println(sw.prettyPrint());

		} catch (Exception e) {
			log.error("", e);
		}
	}

	private InputStream getOriginImg(String imgId) {
		// 1.获取原始图片
		var originImg = this.getClass().getResourceAsStream("/static/" + imgId);

		// 从ftp 下载原图
		// var outOriginImg = new ByteArrayOutputStream();
		// UploadUtil.download(OutputStream outOriginImg, String path, String name)
		// var originImg=new ByteArrayInputStream(outOriginImg.toByteArray());

		return originImg;
	}



}
